package com.nacos.utils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;

import java.util.Properties;

/**
 * @author nkorange
 */
public class NamingExample {

    public static void main(String[] args) throws NacosException {

        Properties properties = new Properties();
        properties.setProperty("serverAddr", "localhost:8848");
//        properties.setProperty("namespace", null);

        NamingService naming = NamingFactory.createNamingService(properties);

        naming.registerInstance("produce-service", "11.11.11.11", 8888, "TEST1");

        naming.registerInstance("produce-service", "2.2.2.2", 9999, "DEFAULT");

        System.out.println(naming.getAllInstances("produce-service"));

        //删除服务下的一个实例。
//        naming.deregisterInstance("produce-service", "2.2.2.2", 9999, "DEFAULT");

        System.out.println(naming.getAllInstances("produce-service"));

        naming.subscribe("produce-service", new EventListener() {
            @Override
            public void onEvent(Event event) {
                System.out.println(((NamingEvent) event).getServiceName());
                System.out.println(((NamingEvent) event).getInstances());
            }
        });
    }
}